package com.ruoyi.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.ruoyi.auth.form.MerchantLoginBody;

import com.ruoyi.bigbase.api.RemoteCustomerService;
import com.ruoyi.bigbase.api.domain.Customer;
import com.ruoyi.bigbase.api.domain.IntegralDetails;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.merchant.api.RemoteMerchantService;
import com.ruoyi.merchant.api.domain.Merchant;
import com.ruoyi.merchant.api.domain.MerchantImgs;
import com.ruoyi.merchant.api.domain.MerchantVerification;
import com.ruoyi.system.api.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.auth.form.LoginBody;
import com.ruoyi.auth.form.RegisterBody;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.auth.AuthUtil;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;

import java.util.*;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private RemoteMerchantService remoteMerchantService;

    @Autowired
    private RemoteCustomerService remoteCustomerService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("merchantlogin")
    public R<?> merchantlogin(@RequestBody MerchantLoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.merchantlogin(form.getPhone(), form.getCode());
        // 获取登录token

        HashMap<String, Object> objectObjectHashMap = new HashMap<>();

        objectObjectHashMap.put("token", tokenService.createToken(userInfo));
        MerchantVerification merchantByPhone = remoteMerchantService.getMerchantByPhone(userInfo.getSysUser().getPhonenumber(), SecurityConstants.INNER);
        if (merchantByPhone == null) {
            throw new ServiceException("未查询到该商户信息");
        }

        objectObjectHashMap.put("merchant", merchantByPhone);
        return R.ok(objectObjectHashMap);
    }


    //客户端登录
    @PostMapping("customerLogin")
    public R<?> customerLogin(@RequestBody LoginBody form) {
//        System.out.println("111"+form.getUsername());
//        System.out.println(form.getUsername().contains("@"));
        if (form.getUsername().contains("@"))
            form.setUsername(remoteUserService.getUsernameByEmail(form.getUsername(), SecurityConstants.INNER));
        else if (form.getUsername().length() == 11 && form.getUsername().matches("^1[0-9]{10}$"))
            form.setUsername(remoteUserService.getUsernameByPhone(form.getUsername(), SecurityConstants.INNER));
//        System.out.println("222"+form.getUsername());
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
//        System.out.println(userInfo.getSysUser());
        String remark = userInfo.getSysUser().getRemark();
//        System.out.println(remark);
        if (!remark.contains("customer"))
            return R.fail("此账号非客户端账号");
//        System.out.println(remark.substring(8));
        //获取用户信息
        R<Customer> customerInfo = remoteCustomerService.getCustomerInfo(Integer.parseInt(remark.substring(8)), SecurityConstants.INNER);

        if (customerInfo.getCode() != 200 || customerInfo.getData() == null)
            return R.fail("用户信息获取失败");
        Customer customer = customerInfo.getData();
        Integer status = customerInfo.getData().getStatus();
        if (status == -1)
            return R.fail("此账号已被封禁");
            //正常用户，签到
        else if (status == 1) {
            Integer oneDay = remoteCustomerService.getTimeByUserId(Integer.parseInt(remark.substring(8)), SecurityConstants.INNER);
            //大于一天加，20积分
            if (oneDay != null && oneDay > 0) {
                IntegralDetails integralDetails = new IntegralDetails();
                integralDetails.setUserId(Integer.parseInt(remark.substring(8)));
                integralDetails.setScore(20);
                integralDetails.setContent("每日签到");
                AjaxResult ajaxResult = remoteCustomerService.addPoints(integralDetails, SecurityConstants.INNER);
                //更新用户积分
                if (ajaxResult.isSuccess()) {
                    customer.setPoints(customer.getPoints() + 20);
                }
            }
        }

        // 获取登录token
        Map<String, Object> tokenMap = tokenService.createToken(userInfo);
        Object token = tokenMap.get("access_token");
        String s = token.toString();
        return R.ok(customer, s);
    }


    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    @PostMapping("MerchantRegister")
    public R<?> MerchantRegister(@RequestBody Map<String, Object> registerBody) {
        System.out.println(registerBody.toString());
        // 用户注册
        boolean merchantregister = sysLoginService.merchantregister((String) registerBody.get("director"), (String) registerBody.get("mobile"), "123456");
        if (merchantregister) {
            Merchant merchant = new Merchant();
            merchant.setName(registerBody.get("name").toString());
            merchant.setRegTime(new Date());
            merchant.setAddress(registerBody.get("address").toString());
            merchant.setOperatingArea(registerBody.get("operatingArea").toString());
            merchant.setDescription(registerBody.get("description").toString());
            merchant.setDel(0L);
            merchant.setStatus(0L);
            merchant.setAuditStatusId(0L);
            AjaxResult ajaxResult = remoteMerchantService.merchantAdd(merchant, SecurityConstants.INNER);
            if (ajaxResult.isSuccess()) {
                MerchantVerification merchantVerification = new MerchantVerification();
                merchantVerification.setDirector(registerBody.get("director").toString());
                merchantVerification.setIdCard(registerBody.get("idCard").toString());
                merchantVerification.setMobile(registerBody.get("mobile").toString());
                merchantVerification.setBusinessLicenseId(registerBody.get("businessLicenseId").toString());
                merchantVerification.setBusinessLicenseImg(registerBody.get("businessLicenseImg").toString());
                merchantVerification.setFront(registerBody.get("front").toString());
                merchantVerification.setOpposite(registerBody.get("opposite").toString());
                merchantVerification.setMid(Long.valueOf(ajaxResult.get("data").toString()));
                AjaxResult ajaxResult1 = remoteMerchantService.MerchantVerificationAdd(merchantVerification, SecurityConstants.INNER);
                if (ajaxResult1.isSuccess()) {
                    String[] strings=(String[]) registerBody.get("facadePhoto");
                    List<MerchantImgs> merchantImgs=new ArrayList<>();
                    for (String string : strings) {
                        if(merchantImgs.size()>9){
                        break;
                        }
                        merchantImgs.add(new MerchantImgs(Long.valueOf(ajaxResult.get("data").toString()),string));
                    }
                    AjaxResult addimgs = remoteMerchantService.addimgs(merchantImgs, SecurityConstants.INNER);
                    if (addimgs.isSuccess()){
                        return R.ok();
                    }
                return R.fail("imgs注册失败");
                }
                return R.fail("Verification注册失败");
            }
            return R.fail("merchant注册失败");
        }
        return R.fail("user注册失败");
    }
}
